package com.example.demo.paper.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.utils.CacheProvider;
import com.example.demo.exception.ZException;
import com.example.demo.enums.ErrorEnum;
import com.example.demo.paper.entity.TPaper;
import com.example.demo.paper.mapper.TPaperMapper;
import com.example.demo.paper.service.ITPaperService;
import com.example.demo.paper_answer.entity.RPaperAnswer;
import com.example.demo.paper_answer.mapper.RPaperAnswerMapper;
import com.example.demo.questions.service.ITQuestionsService;
import com.example.demo.utils.ZUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 试卷表 服务实现类
 * </p>
 *
 * @author zhongz
 * @since 2019-02-16
 */
@Service
public class TPaperServiceImpl extends ServiceImpl<TPaperMapper, TPaper> implements ITPaperService {
    @Resource
    private ITQuestionsService questionsService;

    @Resource
    private TPaperMapper paperMapper;

    @Resource
    private RPaperAnswerMapper paperAnswerMapper;

    /**
     * 获取列表
     *
     * @param pagination 页码
     * @param size       每页显示
     * @return
     */
    @Override
    public IPage<Map<String, Object>> getList(Integer pagination, Integer size) {
        Page<TPaper> page = new Page<>(pagination, size);
        QueryWrapper<TPaper> paperWrapper = new QueryWrapper<>();
        paperWrapper.isNotNull("FINISH_DATETIME");
        paperWrapper.orderByDesc("CREATE_DATETIME");
        return this.pageMaps(page, paperWrapper);
    }

    /**
     * 获取试卷详情
     *
     * @param paperId 试卷id
     * @return
     */
    @Override
    public List<Map<String, Object>> getDetail(String paperId) throws ZException {
        // 校验参数
        if (StringUtils.isEmpty(paperId)) {
            throw new ZException(ErrorEnum.LACK_PARAM);
        }

        // 查询试卷信息
        TPaper paper = this.getById(paperId);
        if (paper == null) {
            throw new ZException(ErrorEnum.CANT_FIND);
        }
        // 查询试卷中考题的信息
        List<Map<String, Object>> detail = paperMapper.selectPaperDetail(paperId);

        // 整理返回的数据
        detail.forEach(map -> {
            // 将答案id与答案内容整合
            String[] ansIdArr = StringUtils.split(map.get("ansIds").toString(), ",");
            String[] ansContentArr = StringUtils.split(map.get("ansContents").toString(), ",");
            List<Map<String, String>> ansList = new ArrayList<>();
            for (int i = 0; i < ansIdArr.length; i++) {
                Map<String, String> mapTemp = new HashMap<>();
                mapTemp.put("ansId", ansIdArr[i]);
                mapTemp.put("ansContent", ansContentArr[i]);
                ansList.add(mapTemp);
            }
            map.put("answers", ansList);
        });

        return detail;
    }

    /**
     * 提交试卷
     *
     * @param paperId    试卷id
     * @param records    答题记录
     * @param rightCount 正确数
     * @param wrongCount 错误数
     * @param spendTime  花费时间
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean finishPaper(String paperId, String records, Integer rightCount, Integer wrongCount, Integer spendTime) throws Exception {
        // 根据试卷id更新
        TPaper paper = new TPaper();
        paper.setId(paperId);
        if (spendTime != null) {
            paper.setSpendTime(spendTime);
        }
        paper.setWrongCount(wrongCount);
        paper.setRightCount(rightCount);
        paper.setFinishDatetime(ZUtils.getNowDateTimeStr());
        paperMapper.updateById(paper);

        // 修改试卷与答案关系表中数据
        List<Map> checkedList = JSON.parseArray(records, Map.class);
        checkedList.forEach(map -> {
            QueryWrapper<RPaperAnswer> wrapper = new QueryWrapper<>();
            wrapper.eq("PAPER_ID", paperId).eq("QUESTION_ID", map.get("id").toString());
            RPaperAnswer paperAnswer = new RPaperAnswer();
            paperAnswer.setAnswerId(map.get("checkedAnswer").toString());
            paperAnswerMapper.update(paperAnswer, wrapper);
        });
        return true;
    }

    /**
     * 缓存回答试卷数据
     *
     * @param paperId 试卷id
     * @param records 试卷数据
     */
    @Override
    public void cachePaper(String paperId, String records) {
        Map<String, Object> model = new HashMap<>();
        model.put("paperId", paperId);
        try {
            model.put("records", URLDecoder.decode(records, "UTF8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CacheProvider.set("cachePaper", JSON.toJSONString(model), 86400L);
    }
}
